//package com.alibaba.cirtus.ots.application.adapter.ability.facade.service.dp.mndataif002;
//
//import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.CustomerAddressSDO;
//import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.CustomerSDO;
//import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.CustomerSaleScopeSDO;
//import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
//import com.alibaba.cz.base.tool.log.Log;
//import com.epoch.app.bcots.model.dto.OrganizationSDO;
//import com.epoch.app.otsapplicationadaptersdk.dp.DpCustmer;
//import com.epoch.app.otsapplicationadaptersdk.dp.MnDataCustmerResponse;
//import com.epoch.app.otsapplicationadaptersdk.dp.MnDataCustmerSDO;
//import com.epoch.app.otsapplicationadaptersdk.dp.mndataif002electricity.dto.DoHandlerRequest;
//import com.epoch.app.otsapplicationadaptersdk.dp.mndataif002electricity.service.MnDataIf002ElectricityService;
//import com.epoch.app.otsapplicationadaptersdk.model.dto.RestDpCustmerDataElectricityRequest;
//import com.epoch.app.otsapplicationadaptersdk.service.DpService;
//import com.epoch.app.otsplatformenhance.domain.customer.model.Customer;
//import org.apache.commons.collections4.CollectionUtils;
//import org.apache.commons.compress.utils.Lists;
//import org.jetbrains.annotations.NotNull;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.annotation.Resource;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//import java.util.Objects;
//import java.util.Set;
//import java.util.stream.Collectors;
//
///**
// * @author zhoubc
// * @description: 售达方电商同步
// * @date 2021/9/25 1:08
// */
//@Component
//public class MnDataIf002ElectricityServiceImpl implements MnDataIf002ElectricityService {
//    Log log = Log.getLogger(MnDataIf002ElectricityServiceImpl.class);
//
//    @Resource
//    private MnDataIf002SDOBuilder mnDataIf002SdoBuilder;
//
//    @Resource
//    private MnDataIf002SyncUtils mnDataIf002SyncUtils;
//
//    @Resource
//    private DpService dpService;
//
//    @ProcessInvoker(remark = "MnDataIf002ElectricityService", errorCode = "", printLog = true)
//    @Override
//    @Transactional
//    public Object doHandler(DoHandlerRequest doHandlerRequest) {
//        // 1、构造中台查询参数
//        RestDpCustmerDataElectricityRequest param = buildMnQueryMap(doHandlerRequest);
//        //调用中台接口获取客户主数据
//        MnDataCustmerResponse mnDataCustmerResponse = getMnDataCustmerResponse(param);
//        // 总页数
//        MnDataCustmerSDO data = mnDataCustmerResponse.getData();
//        if (Objects.isNull(data) || CollectionUtils.isEmpty(data.getRows())) {
//            return mnDataCustmerResponse;
//        }
//        int totalPage = getTotalPage(data);
//
//        long before = System.currentTimeMillis();
//        log.info("电商售达方同步开始，总条数:{},共{}页", data.getTotalNum(), totalPage);
//        //分页同步客户主数据
//        for (int current = 1; current <= totalPage; current++) {
//            log.info("电商售达方同步开始，开始同步第{}页", current);
//            param.setPageNum(String.valueOf(current));
//            long start = System.currentTimeMillis();
//            MnDataCustmerResponse customerRes = getMnDataCustmerResponse(param);
//            //判空
//            if (Objects.isNull(customerRes.getData()) || CollectionUtils.isEmpty(customerRes.getData().getRows())) {
//                continue;
//            }
//            List<DpCustmer> mnCustomers = customerRes.getData().getRows();
//            try {
//                syncCurrentPageOfCustomer(mnCustomers);
//            } catch (Exception e){
//                log.error("MnDataIf002ElectricityServiceImpl#doHandler_fail " + "同步电商售达方异常");
//                throw e;
//            }
//            log.info("电商售达方第{}页同步结束,用时{}", current, System.currentTimeMillis() - start);
//        }
//        log.info("电商售达方同步结束，耗时:{}", System.currentTimeMillis() - before);
//        return mnDataCustmerResponse;
//    }
//
//    @NotNull
//    private MnDataCustmerResponse getMnDataCustmerResponse(RestDpCustmerDataElectricityRequest param) {
//        MnDataCustmerResponse mnDataCustmerResponse = null;
//        int retryTimes = 0;
//        String errCode = null;
//        do {
//            if("1108113002".equals(errCode)) {
//                try {
//                    Thread.sleep(120000);
//                } catch (InterruptedException e) {
//                    log.error("MnDataIf002ElectricityServiceImpl#doHandler InterruptedException", e);
//                }
//            }
//            mnDataCustmerResponse = dpService.restDpCustmerDataElectricity(param);
//            errCode = mnDataCustmerResponse.getErrCode();
//        } while (!"0".equals(errCode) && retryTimes ++ < 10);
//        return mnDataCustmerResponse;
//    }
//
//    public void syncCurrentPageOfCustomer(List<DpCustmer> mnCustomers) {
//        //1、查询出所有组织
//        Map<String, OrganizationSDO> organizationMapByCustomers = mnDataIf002SdoBuilder.getOrganizationMapByCustomers(mnCustomers);
//        log.info("syncCurrentPageOfCustomer,request,mnCustomers:{}",mnCustomers);
//        log.info("syncCurrentPageOfCustomer,response,organizationMapByCustomers:{}",organizationMapByCustomers);
//        if (Objects.isNull(organizationMapByCustomers)) {
//            return;
//        }
//        List<CustomerSDO> customerSDOs = Lists.newArrayList();
//        List<CustomerSaleScopeSDO> customerSaleScopeSDOs = Lists.newArrayList();
//        List<CustomerAddressSDO> customerAddressSDOs = Lists.newArrayList();
//        for (DpCustmer dpCustomer : mnCustomers) {
//            CustomerSDO customerSDO = mnDataIf002SdoBuilder.buildCustomerMainDataSDO(dpCustomer, organizationMapByCustomers);
//            if (Objects.isNull(customerSDO)) {
//                continue;
//            }
//            customerSDOs.add(customerSDO);
//            CustomerSaleScopeSDO customerSaleScopeSDO = mnDataIf002SdoBuilder.buildCustomerSaleScopeSDO(dpCustomer, organizationMapByCustomers);
//            if (Objects.isNull(customerSaleScopeSDO)) {
//                continue;
//            }
//            customerSaleScopeSDOs.add(customerSaleScopeSDO);
//        }
//        // 批量保存或者更新客户主档数据
//        batchSaveAndUpdateCustomers(customerSDOs);
//        // 批量保存或者更新客户销售范围
//        batchSaveAndUpdateCustomerScopes(customerSaleScopeSDOs);
//    }
//
//    private void batchSaveAndUpdateAddresses(List<CustomerAddressSDO> customerAddressSDOs) {
//        if (CollectionUtils.isEmpty(customerAddressSDOs)) {
//            return;
//        }
//        List<CustomerAddressSDO> existAddressList = mnDataIf002SyncUtils.batchQueryCustomerAddress(customerAddressSDOs);
//        Map<String, CustomerAddressSDO> existAddressMap = existAddressList.stream().collect(Collectors.toMap((it -> mnDataIf002SyncUtils.getAddressCombineKey(it)), a -> a, (a, b) -> a));
//        List<CustomerAddressSDO> notExistAddresses = customerAddressSDOs.stream().filter(it -> !existAddressMap.containsKey(mnDataIf002SyncUtils.getAddressCombineKey(it))).collect(Collectors.toList());
//        Map<String, CustomerAddressSDO> addressUpdatedMap = customerAddressSDOs.stream().filter(it -> existAddressMap.containsKey(mnDataIf002SyncUtils.getAddressCombineKey(it))).collect(Collectors.toMap(it -> mnDataIf002SyncUtils.getAddressCombineKey(it), a -> a, (a, b) -> a));
//        if (CollectionUtils.isNotEmpty(notExistAddresses)) {
//            Boolean addressSave = mnDataIf002SyncUtils.batchCreateCustomerAddresses(notExistAddresses);
//            log.info("客户送达方批量新增结果:{}", addressSave);
//        }
//        if (CollectionUtils.isNotEmpty(existAddressList)) {
//            Boolean addressUpdated = mnDataIf002SyncUtils.batchUpdateCustomerAddresses(existAddressList, addressUpdatedMap);
//            log.info("客户送达方批量更新结果:{}", addressUpdated);
//        }
//    }
//
//    private void batchSaveAndUpdateCustomerScopes(List<CustomerSaleScopeSDO> customerSaleScopeSDOs) {
//        if (CollectionUtils.isEmpty(customerSaleScopeSDOs)) {
//            return;
//        }
//        List<CustomerSaleScopeSDO> existScopeList = mnDataIf002SyncUtils.batchQueryCustomerScopes(customerSaleScopeSDOs);
//        Map<String, CustomerSaleScopeSDO> existScopeMap = existScopeList.stream().collect(Collectors.toMap((it -> mnDataIf002SyncUtils.getScopeCombineKey(it)), a -> a, (a, b) -> a));
//        List<CustomerSaleScopeSDO> notExistScopes = customerSaleScopeSDOs.stream().filter(it -> !existScopeMap.containsKey(mnDataIf002SyncUtils.getScopeCombineKey(it))).collect(Collectors.toList());
//        Map<String, CustomerSaleScopeSDO> updatedMap = customerSaleScopeSDOs.stream().filter(it -> existScopeMap.containsKey(mnDataIf002SyncUtils.getScopeCombineKey(it))).collect(Collectors.toMap(it -> mnDataIf002SyncUtils.getScopeCombineKey(it), a -> a, (a, b) -> a));
//        if (CollectionUtils.isNotEmpty(notExistScopes)) {
//            Boolean scopeSave = mnDataIf002SyncUtils.batchCreateCustomerScopes(notExistScopes);
//            log.info("客户销售范围批量新增结果:{}", scopeSave);
//        }
//        if (CollectionUtils.isNotEmpty(existScopeList)) {
//            Boolean scopeUpdate = mnDataIf002SyncUtils.batchUpdateCustomerScopes(existScopeList, updatedMap);
//            log.info("客户销售范围批量更新结果:{}", scopeUpdate);
//        }
//    }
//
//    private void batchSaveAndUpdateCustomers(List<CustomerSDO> customerSDOs) {
//        if (CollectionUtils.isEmpty(customerSDOs)) {
//            return;
//        }
//        Set<String> customerCodeSet = customerSDOs.stream().map(CustomerSDO::getCode).collect(Collectors.toSet());
//        List<String> customerCodes = new ArrayList<>(customerCodeSet);
//        List<Customer> existCustomers = mnDataIf002SyncUtils.batchQueryCustomerMainData(customerCodes);
//        Map<String, Customer> existCustomerMap = existCustomers.stream().collect(Collectors.toMap(Customer::getCode, a -> a, (a, b) -> a));
//        Map<String, CustomerSDO> updateMap = customerSDOs.stream().filter(it -> existCustomerMap.containsKey(it.getCode())).collect(Collectors.toMap(CustomerSDO::getCode, a -> a, (a, b) -> a));
//        List<CustomerSDO> notExistCustomers = customerSDOs.stream().filter(it -> !existCustomerMap.containsKey(it.getCode())).collect(Collectors.toList());
//        // 处理新增的客户
//        if (CollectionUtils.isNotEmpty(notExistCustomers)) {
//            Boolean save = mnDataIf002SyncUtils.batchCreateCustomers(notExistCustomers);
//            log.info("客户主数据批量新增结果:{}", save);
//        }
//        if (CollectionUtils.isNotEmpty(existCustomers)) {
//            Boolean update = mnDataIf002SyncUtils.batchUpdateCustomers(existCustomers, updateMap);
//            log.info("客户主数据批量更新结果:{}", update);
//        }
//    }
//
//    public int getTotalPage(MnDataCustmerSDO data) {
//        Integer totalNum = data.getTotalNum();
//        Integer pageSize = data.getPageSize();
//        int totalPage = 1;
//        if (totalNum % pageSize == 0) {
//            totalPage = totalNum / pageSize;
//        } else {
//            totalPage = (totalNum / pageSize) + 1;
//        }
//        return totalPage;
//    }
//
//    private RestDpCustmerDataElectricityRequest buildMnQueryMap(DoHandlerRequest doHandlerRequest) {
//        RestDpCustmerDataElectricityRequest dataElectricityRequest = RestDpCustmerDataElectricityRequest.builder()
//                .ds(doHandlerRequest.getDs())
//                .fromSys(doHandlerRequest.getFromSys())
//                .pageNum(doHandlerRequest.getPageNum())
//                .pageSize(doHandlerRequest.getPageSize()).build();
////        if (StringUtils.isEmpty(dataElectricityRequest.getDs())) {
////            String yesterday = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDateTime.now().plusDays(-1));
////            dataElectricityRequest.setDs(yesterday);
////        }
//        return dataElectricityRequest;
//    }
//}
